package com.vlin.scene.actuator.defaut;

import java.util.Map;

import org.json.JSONObject;

import com.vlin.entity.scene.Automation;
import com.vlin.entity.scene.Command;
import com.vlin.entity.scene.DefaultScene;
import com.vlin.entity.scene.Scene;
import com.vlin.entity.scene.TimerEvent;
import com.vlin.scene.actuator.AbstractSceneResolver;

public class DefaultSceneResolver extends AbstractSceneResolver {

	@Override
	public boolean doSupport(Scene scene) {
		
		
		return DefaultScene.class.isAssignableFrom(scene.getClass());
	}

	@Override
	public TimerEvent doResolve(Scene scene) {

		DefaultScene defaut = (DefaultScene) scene;
		Map<Integer, String> map = defaut.getCommands();
		
		TimerEvent result = new TimerEvent();
		result.setDelay(0L);
		TimerEvent event = result;

		for (int i = map.size() - 1; i >= 0; i--) {
			String v= map.get(i);
			JSONObject value = new JSONObject(v);
			int type = value.getInt("type");//type为 1，说明是定时
			if(type != 1) {
				JSONObject command = value;
				Command cmd = getListCommandProducer().produce(command);
				if(cmd != null) {
					event.addCommand(cmd);
				}
			}else {
				TimerEvent next = new TimerEvent();
				event.setEvent(next);
				event = next;
				long delay = value.getLong("delay");
				next.setDelay(delay);
			}
		}

		return result;
	}

	@Override
	public boolean doSupport(Automation automation) {
		
		return Automation.class.isAssignableFrom(automation.getClass());
	}

	@Override
	public TimerEvent doResolve(Automation automation) {
		Map<Integer, String> map = automation.getCommands();
		
		TimerEvent result = new TimerEvent();
		result.setDelay(0L);
		TimerEvent event = result;

		for (int i = map.size() - 1; i >= 0; i--) {
			String v= map.get(i);
			JSONObject value = new JSONObject(v);
			int type = value.getInt("type");//type为 1，说明是定时
			if(type != 1) {
				JSONObject command = value;
				Command cmd = getListCommandProducer().produce(command);
				if(cmd != null) {
					event.addCommand(cmd);
				}
			}else {
				TimerEvent next = new TimerEvent();
				event.setEvent(next);
				event = next;
				long delay = value.getLong("delay");
				next.setDelay(delay);
			}
		}

		return result;
	}

}
